/**
 * 提煤单管理列表页面
 * @author xiaoxujs
 */

// components
import SearchModule from "./components/SearchModule"; //检索模块

import {
  Button,
  ConfigProvider,
  message,
  Space,
  Table,
  TableProps,
  Upload,
  UploadProps,
} from "antd";
import { PaichedanManagementListBox, PMListBox, PMTitleBox } from "./style";
import { useCallback, useEffect, useState } from "react";
import type {
  IPcdZyVehicleInfoSelect,
  IPcdZyVehicleInfoSelectParams,
  IPcdZyVehicleInfoSelectParamsForm,
} from "../../../type/paichedan";
import {
  getPcdZyVehicleInfoDelete,
  getPcdZyVehicleInfoDownloadTemplateUrl,
  postPcdZyVehicleInfoSelect,
} from "../api";
import { IFenye } from "../../../type/commit";
import { TablePaginationPosition } from "../../../type/antd";
import AddAndChangeModule from "./components/AddAndChangeModule";
import { handleGetDictionaryItemValue } from "../../../assets/fun/DictionaryItem";
import { inputType, vehicleType } from "../../../assets/data";
import { handleDeleteAssets } from "../../../assets/fun/Antd/deleteFun";
import { gethandleTemplateDownload } from "../../../assets/fun/fileDownloadFun";
import { basicIp } from "../../../api/http";
import { handleUploadFileRestrictions } from "../../../assets/fun/Antd/file";

const PaichedanManagementList = () => {
  const contentValue: TablePaginationPosition = "bottomCenter"; //位置

  const [paging, setPaging] = useState({
    //分页
    currentPage: 1,
    pageSize: 10,
  });
  const [listData, setListData] = useState<IPcdZyVehicleInfoSelect[]>();
  const [total, setTotal] = useState(0);
  const [addAndChangeModuleShow, setAddAndChangeModuleShow] = useState(false); // 添加 编辑 弹窗
  const [clickData, setClickData] = useState<IPcdZyVehicleInfoSelect>(); //  点击编辑data
  const [searchData, setSearchData] =
    useState<IPcdZyVehicleInfoSelectParamsForm>(); // 筛选条件
  const [tableLoading, setTableLoading] = useState(false); //tableLoading
  const [mobanxiazaiLoading, setMobanxiazaiLoading] = useState(false); // 模板下载loading

  const listFun = useCallback(async (params: IPcdZyVehicleInfoSelectParams) => {
    setTableLoading(true);
    const { code, msg, data } = (await postPcdZyVehicleInfoSelect(
      params
    )) as IFenye<IPcdZyVehicleInfoSelect>;
    if (code === 20000) {
      setListData(data.records);
      setTotal(data.total);
      setPaging({
        currentPage: params.currentPage,
        pageSize: params.pageSize,
      });
      setTableLoading(false);
    } else {
      message.error(msg);
    }
  }, []);

  useEffect(() => {
    const params = {
      currentPage: 1,
      pageSize: 10,
    };
    listFun(params);
  }, [listFun]);

  // 检索回调函数
  const handleSearchCallback = (data: IPcdZyVehicleInfoSelectParamsForm) => {
    const params = {
      ...data,
      currentPage: 1,
      pageSize: 10,
    };
    listFun(params);
    setSearchData(data);
  };
  // 添加 、 编辑 回调函数
  const handleAddAndChangeModuleCallback = () => {
    setClickData(undefined);
    setAddAndChangeModuleShow(false);
    const params = {
      searchData,
      currentPage: paging.currentPage,
      pageSize: paging.pageSize,
    };
    listFun(params);
  };
  // 删除数据
  const handleDelete = (id: string) => {
    handleDeleteAssets(
      async () => {
        return (await getPcdZyVehicleInfoDelete({ id })) as {
          code: number;
          msg: string;
        };
      },
      () => {
        const params = {
          searchData,
          currentPage: paging.currentPage,
          pageSize: paging.pageSize,
        };
        listFun(params);
      }
    );
  };
  // 文件拖拽上传
  const dianjiProps: UploadProps = {
    name: "file", //上传名字
    action: basicIp + "/pcd/zy-vehicle-info/importExcel", // 上传地址
    method: "put", // 上传方法
    maxCount: 1, // 页面显示最多条数
    headers: {
      satoken: sessionStorage.getItem("token")!, // 请求头
      checkType: "ck-token-auth",
    },
    showUploadList: false,
    beforeUpload: (file) => handleUploadFileRestrictions(file, { size: 100 }),
    onChange(info) {
      let newFileList = [...info.fileList];
      newFileList.map((file) => {
        if (file.response) {
          if (file.response.code === 20000) {
            const params = {
              currentPage: 1,
              pageSize: 10,
            };
            listFun(params);
            message.success("导入成功");
            file.status = "done";
          } else {
            message.error(file.response.msg);
            file.status = "error";
          }
        }
        return file;
      });
    },
  };

  const pagination = {
    //分页
    position: [contentValue],
    //是否可以改变pagesize//
    showSizeChanger: true,
    //是否可以快速跳转到某页
    // showQuickJumper: true,
    //展示一共有多少条数据//
    showTotal: () => `共${total}条`,
    //每页条数
    pageSize: paging.pageSize,
    //当前页数
    current: paging.currentPage,
    //数据总数
    total: total,
    //页码改变的回调，参数是改变后的页码及每页条数
    onChange: (current: number, pageSize: number) => {
      const params = {
        ...searchData,
        currentPage: current,
        pageSize: pageSize,
      };
      listFun(params);
      // setPaging({
      //     currentPage: current,
      //     pageSize: pageSize,
      // });
    },
  };
  const columns: TableProps<IPcdZyVehicleInfoSelect>["columns"] = [
    {
      title: "序号",
      align: "center",
      render: (text, record, index) => (
        <span>{paging.currentPage * paging.pageSize - 10 + index + 1}</span>
      ),
    },
    {
      title: "派车单编号",
      align: "center",
      dataIndex: "dispatchNum",
    },
    {
      title: "车牌号",
      align: "center",
      render: (_, record) => (
        <span>{record.plateColor + record.plateNumber}</span>
      ),
    },
    {
      title: "车斗长(m)",
      align: "center",
      dataIndex: "carDollyLength",
    },
    {
      title: "车斗宽(m)",
      align: "center",
      dataIndex: "carDollyWidth",
    },
    {
      title: "车斗高(m)",
      align: "center",
      dataIndex: "carDollyHeight",
    },
    {
      title: "车型",
      align: "center",
      dataIndex: "carType",
      render: (text) => (
        <span>{handleGetDictionaryItemValue(vehicleType, text)}</span>
      ),
    },
    {
      title: "预装量(吨)",
      align: "center",
      dataIndex: "preloadAmount",
    },
    {
      title: "司机姓名",
      align: "center",
      dataIndex: "driverName",
    },
    {
      title: "电话",
      align: "center",
      dataIndex: "contactNumber",
    },
    {
      title: "允许提煤日期",
      align: "center",
      dataIndex: "allowDate",
    },
    {
      title: "提煤状态",
      align: "center",
      dataIndex: "isEnd",
      render: (text) => <span>{text === 0 ? "进行中" : "已结束"}</span>,
    },
    {
      title: "录入方式",
      align: "center",
      dataIndex: "inputType",
      render: (text) => (
        <span>{handleGetDictionaryItemValue(inputType, text)}</span>
      ),
    },
    {
      title: "物料名称",
      align: "center",
      dataIndex: "materialName",
    },
    {
      title: "操作",
      align: "center",
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="link"
            onClick={() => {
              setClickData(record);
              setAddAndChangeModuleShow(true);
            }}
          >
            编辑
          </Button>
          <Button type="link" onClick={() => handleDelete(record.id)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];
  return (
    <PaichedanManagementListBox>
      <PMTitleBox>
        <div className="title">提煤单管理</div>
        <div>
          <Button
            style={{ marginLeft: "2rem" }}
            icon={<span className="iconfont">&#xe60e;</span>}
            loading={mobanxiazaiLoading}
            onClick={() => {
              setMobanxiazaiLoading(true);
              gethandleTemplateDownload(
                getPcdZyVehicleInfoDownloadTemplateUrl,
                {
                  type: "1",
                },
                "xlsx",
                "arraybuffer",
                () => {
                  setMobanxiazaiLoading(false);
                }
              )
            }

            }
          >
            模板下载
          </Button>
          <Upload {...dianjiProps}>
            <Button
              style={{ marginLeft: "2rem" }}
              icon={<span className="iconfont">&#xe65f;</span>}
            >
              批量导入
            </Button>
          </Upload>
          <Button
            type="primary"
            style={{ marginLeft: "2rem" }}
            icon={<span className="iconfont">&#xe620;</span>}
            onClick={() => setAddAndChangeModuleShow(true)}
          >
            添加车辆
          </Button>
        </div>
      </PMTitleBox>
      <SearchModule handleSearchCallback={handleSearchCallback} />
      <PMListBox>
        <div className="list-title">
          <div className="list-title-text">全部</div>
        </div>
        <ConfigProvider
          theme={{
            components: {
              Table: {
                headerColor: "#8B9BAC",
              },
            },
          }}
        >
          <Table<IPcdZyVehicleInfoSelect>
            columns={columns}
            dataSource={listData}
            rowKey="id"
            pagination={pagination}
            loading={tableLoading}
          />
        </ConfigProvider>
      </PMListBox>
      <AddAndChangeModule
        open={addAndChangeModuleShow}
        handleAddAndChangeModuleCallback={handleAddAndChangeModuleCallback}
        clickData={clickData}
      />
    </PaichedanManagementListBox>
  );
};

export default PaichedanManagementList;
